import pwd
import subprocess
import time

class ConfigureUsers:
    def __init__(self, users):
        self.users = users
        self.successful = 0
        self.failed     = 0
        self.oo_sync    = 0

    def configure(self):
        print "\033[1;36m- Configuring Users\033[1;m"
        runtime_start = time.time()
        users = self.users

        for user in users:
            username   = user
            new_shell  = users[user]['shell']
            new_gid    = users[user]['gid']
            new_groups = users[user]['groups']

            had_to_refresh = False
            # Does the user exist?
            try:
                user_info= pwd.getpwnam(username)
                old_uid   = user_info[2]
                old_gid   = user_info[3]
                old_home  = user_info[5]
                old_shell = user_info[6]
                # User resource in sync?
                if old_shell != new_shell:
                    subprocess.call(['/usr/sbin/usermod', '-s', new_shell, username])
                    had_to_refresh = True
                if old_gid != int(new_gid):
                    subprocess.call(['/usr/sbin/usermod', '-g', new_gid, username])
                    had_to_refresh = True
                self.successful += 1
            except KeyError:
                print "%s does not exsit, creating..." % username
                subprocess.call(['/usr/sbin/useradd', '-s', new_shell, '-G', new_groups, username])
                had_to_refresh = True

        if had_to_refresh:
            self.oo_sync += 1

        # Collect Stats
        runtime_end = time.time()
        runtime = (runtime_end - runtime_start)

        stats = {
            'runtime'   : runtime,
            'successful': self.successful,
            'failed'    : self.failed,
            'oo_sync'   : self.oo_sync
        }

        return stats
